package com.origin.uilibrary.edittext

import android.content.Context
import android.content.res.TypedArray
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.text.method.DigitsKeyListener
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.widget.EditText
import android.widget.TextView
import com.origin.uilibrary.R
import java.lang.NumberFormatException
import java.lang.StringBuilder
import java.util.regex.Matcher
import java.util.regex.Pattern

class NumberEditText : androidx.appcompat.widget.AppCompatEditText {
    constructor(context: Context) : this(context, null) {
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        keyListener = DigitsKeyListener.getInstance("1234567890.-");
        addListener()
        attrs?.apply {
            getAttrs(this);
        }

    }

    var maxNum = Int.MAX_VALUE
    var minNum = 0
    var defaultNum = 0
    fun getAttrs(attrs: AttributeSet) {
        val array: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberEditText)
        maxNum = array.getInt(R.styleable.NumberEditText_maxNum, 0);
        minNum = array.getInt(R.styleable.NumberEditText_minNum, 0);
        defaultNum = array.getInt(R.styleable.NumberEditText_defaultNum, 0);
        array.recycle()
    }

    var buffer = "";
    private fun addListener() {

        setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && getNumber(text.toString()) < minNum) {
                setText(defaultNum.toString())
            }
        }
        addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                buffer = ""
                buffer = text.toString()
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                checkText(text.toString())
            }

            override fun afterTextChanged(s: Editable?) {
                setSelection(text?.length ?: 0);
            }

        })
    }

    val numberRegEx = "^-?[0-9]*\\.?[0-9]*\$"
    val numberRegExEnd = "^-?[0-9]*\\.\$"
    private fun checkText(str: String) {
        var rs = match(str, numberRegEx)
        if (maxNum != 0
            && minNum < maxNum
            && rs
            && (str != "-")
            && !(match(str, numberRegExEnd))
        ) {
            try {
                val numStr = str.toInt();
                if (numStr > maxNum) {
                    rs = false;
                }
            } catch (e: NumberFormatException) {
                e.stackTrace
            }

        }
        if (!rs) {
            setText(buffer)
        }
    }

    private fun getNumber(str: String): Int {
        try {
            val numStr = str.toInt();
            return numStr;
        } catch (e: NumberFormatException) {
            e.stackTrace
            return defaultNum;
        }
    }


    private fun match(str: String, regEx: String): Boolean {
        val pattern: Pattern = Pattern.compile(regEx)
        val matcher: Matcher = pattern.matcher(str)
        val rs = matcher.matches()
        return rs;
    }
}